/*****************************************************************************
* Keppe Messenger (KMP) Keppe Project-Team User Messaging System
* Copyright (C) 2013-2014 Keppe Project-Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/

#include <QApplication>
#ifdef WIN32MAC_SHARED
#include <QUrl>
#include <QTimer>
#include <QProcess>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include "frmUpdate.h"
#include "UpdateThread.h"
#endif
#include <QStyleFactory>
#include <QMessageBox>
#include <QTranslator>
#include <QSettings>
#include <QFileInfo>
#include <QLocale>
#include <QWidget>
#include <QStyle>
#include <QDebug>
#include <QDir>
#include "frmLogin.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

#ifdef Q_WS_WIN64
    a.setApplicationName("Keppe Messenger (64bit)");
#else
    a.setApplicationName("Keppe Messenger");
#endif
    a.setApplicationVersion("1.0.0-30");

    QSettings settings("Keppe","Keppe Messenger");

    settings.beginGroup("Interface");
    QString language = settings.value("Language","System").toString();
    settings.endGroup();

    bool trsf = false;
    QTranslator appTranslator;
    if (language == "System" || language.trimmed() == "")
    {
        QString languageName = QLocale::system().name();
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(":/tr/qt_" + langList.at(0) + ".qm"))
            {
                appTranslator.load(":/tr/qt_" + langList.at(0) + ".qm");
            }
        }
    }
    else
    {
        QString languageName = language;
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(":/tr/qt_" + langList.at(0) + ".qm"))
            {
                if (!appTranslator.load(":/tr/qt_" + langList.at(0) + ".qm"))
                {
                    if (langList.at(0) != "en")
                    {
                        trsf = true;
                    }
                }
            }
            else
            {
                if (langList.at(0) != "en")
                {
                    trsf = true;
                }
            }
        }
    }
    if (trsf)
    {
        QString languageName = QLocale::system().name();
        QStringList langList = languageName.split("_");
        if (langList.length() >= 1)
        {
            if (QFile::exists(":/tr/qt_" + langList.at(0) + ".qm"))
            {
                appTranslator.load(":/tr/qt_" + langList.at(0) + ".qm");
            }
        }
    }
    a.installTranslator(&appTranslator);

    bool noupdate = false;
    bool regupdate = false;
    bool minimized = false;
    bool resetstyle = false;

    foreach (const QString& argument, a.arguments())
    {
        if (argument == "--noupdate" || argument.left(11) == "--noupdate=")
        {
            noupdate = true;
        }
        if (argument == "--regupdate" || argument.left(12) == "--regupdate=")
        {
            regupdate = true;
        }
        if (argument == "--minimized" || argument.left(12) == "--minimized=")
        {
            minimized = true;
        }
        if (argument == "--resetstyle" || argument.left(13) == "--resetstyle=")
        {
            resetstyle = true;
        }
    }

#ifdef SHARED
    QDir pluginsDir = QFileInfo(a.applicationFilePath()).absoluteDir();
    QDir::setCurrent(pluginsDir.path());
    pluginsDir.cd("plugins");
    a.addLibraryPath(pluginsDir.path());
#ifdef QT5
    pluginsDir.cdUp();
    pluginsDir.cd("platforms");
    a.addLibraryPath(pluginsDir.path());
#endif
#ifdef MACX
    pluginsDir.cdUp();
    pluginsDir.cdUp();
    pluginsDir.cd("plugins");
    a.addLibraryPath(pluginsDir.absolutePath());
#ifdef QT5
    pluginsDir.cdUp();
    pluginsDir.cd("platforms");
    a.addLibraryPath(pluginsDir.path());
#endif
#endif

#ifdef WIN32
    if (regupdate)
    {
        QString applicationID;
#ifdef QT5
        applicationID = "{490D16AC-E002-40EA-A563-94B5AC5B5D21}";
#else
#ifdef WIN64
        applicationID = "{6932EC7F-0EB0-4C59-A93C-4D266B8D26DC}";
#elif defined(MSVC)
        applicationID = "{4EA7A8DA-17A3-4466-9D8E-9E635FD85583}";
#else
        applicationID = "{EE2292A2-0CCC-492F-BB0E-F104F972DC1B}";
#endif
#endif
        QSettings regNormal("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\"+applicationID+"_is1",QSettings::NativeFormat);
        if (regNormal.contains("DisplayName"))
        {
            regNormal.setValue("DisplayName",a.applicationName() + " " + a.applicationVersion());
        }
        if (regNormal.contains("DisplayVersion"))
        {
            regNormal.setValue("DisplayVersion",a.applicationVersion());
        }
        QSettings reg6432Node("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\"+applicationID+"_is1",QSettings::NativeFormat);
        if (reg6432Node.contains("DisplayName"))
        {
            reg6432Node.setValue("DisplayName",a.applicationName() + " " + a.applicationVersion());
        }
        if (reg6432Node.contains("DisplayVersion"))
        {
            reg6432Node.setValue("DisplayVersion",a.applicationVersion());
        }
    }
#else
    Q_UNUSED(noupdate);
    Q_UNUSED(regupdate);
#endif

    if (resetstyle)
    {
        settings.beginGroup("Style");
        settings.setValue("Custom", false);
        settings.setValue("showBug", true);
        settings.endGroup();
    }

    QString versionType;

#ifdef MACX
    versionType = "mxqt4";
#else
#ifdef UNIX
    versionType = "unixqt";
#else
#ifdef QT5
    versionType = "64qt5";
#else
#ifdef WIN64
    versionType = "64qt4";
#elif defined(MSVC)
    versionType = "vcqt4";
#else
    versionType = "32qt4";
#endif
#endif
#endif
#endif

#ifdef WIN32

    if (!noupdate)
    {
#ifdef ALPHA_UPDATE_MODE
        bool updateAvailable = false;
        QString newVersion;

        QNetworkAccessManager *http = new QNetworkAccessManager();
        QNetworkReply *treply = http->get(QNetworkRequest(QUrl("http://msg.keppe.org/update/stable" + versionType)));
        QEventLoop loop;
        QTimer::singleShot(5000, &loop, SLOT(quit()));
        QObject::connect(treply, SIGNAL(finished()), &loop, SLOT(quit()));
        loop.exec();

        newVersion = QString::fromUtf8(treply->readAll());
        newVersion = newVersion.remove("\n");
        newVersion = newVersion.remove("\r");
        newVersion = newVersion.trimmed();

        if (a.applicationVersion() != newVersion && newVersion != "") {updateAvailable = true;}

        if (updateAvailable)
        {
            QStringList args;
            args.append("/C");
            args.append("KeppeScriptUpdater.exe --path=network --script=http://msg.keppe.org/update/" + versionType + "_" + newVersion + ".lua --version=" + a.applicationVersion());
            QProcess *ksu = new QProcess;
            ksu->startDetached("cmd",args);
            ksu->deleteLater();
            return 0;
        }
#endif
    }

#endif
#endif

    settings.beginGroup("Style");
    bool loadCustom = settings.value("Custom",false).toBool();
    if (loadCustom)
    {
        QString style = settings.value("Name","System").toString();
        if (style != "System")
        {
            if (style.trimmed() != "")
            {
                a.setStyle(style);
            }
        }
    }
    settings.endGroup();

    frmLogin w;

#ifdef WIN32MAC_SHARED
    settings.beginGroup("Update");
    bool updateNotificationEnabled = settings.value("UpdateNotification",true).toBool();

    frmUpdate *uw = new frmUpdate();
    uw->setVersionType(versionType);

    UpdateThread *ut = new UpdateThread(versionType, a.applicationVersion());
    if (updateNotificationEnabled)
    {
        ut->start();
    }
    else
    {
        uw->disableUpdateNotificationButton();
    }

    w.setUpdateThread(ut);

    QObject::connect(ut,SIGNAL(setNewVersion(QString)),uw,SLOT(setNewVersion(QString)));
    QObject::connect(ut,SIGNAL(updateIsNowAvailable()),uw,SLOT(show()));
    QObject::connect(uw,SIGNAL(disableUpdateNotification()),ut,SLOT(disableUpdateNotification()));

    settings.endGroup();
#endif

    if (minimized)
    {
        w.showMinimized();
    }
    else
    {
        w.show();
    }

    return a.exec();
}
